<template>
  <div class="confirm-order">
    <div class="address">
      <van-cell title="收货地址" is-link @click="area.show = true" :value="area.province ? area.province + area.city + area.area : '请选择收货地址'" />
      <van-field label="详细地址" label-width="80px" v-model="address" placeholder="请输入详细地址" type="text"></van-field>
      <img class="line" src="@assets/images/line.png" alt="" />
    </div>
    <div class="order-info">
      <div class="order-detail">
        <div class="left">
          <img src="@assets/images/good.png" alt="" />
          <div class="order-content">
            <p>企业服务礼包</p>
            <p>下单后3天内发货</p>
          </div>
        </div>
        <div class="right">X1</div>
      </div>
      <van-cell title="订单运费" value="包邮" />
      <van-field rows="4" label="订单留言" placeholder="选填，建议与商家协商一致" v-model="note" type="textarea"></van-field>
    </div>
    <van-button block color="#FE9200" class="apply-btn" @click="applyOrder">提交订单</van-button>
    <van-popup v-model="area.show" round position="bottom">
      <van-area title="" :area-list="areaList" @cancel="area.show = false" @confirm="confirmArea" />
    </van-popup>
    <van-dialog v-model="showPayDialog" title="选择支付方式" show-cancel-button confirmButtonColor="#FE9100" :before-close="handlePay">
      <div class="dialog-container">
        <van-radio-group v-model="payWay">
          <van-cell clickable @click="payWay = 1">
            <template #title>
              <img src="@assets/images/wx.png" alt="" />
              <span>微信支付</span>
            </template>
            <template #right-icon>
              <van-radio :name="1" checked-color="#07c160" />
            </template>
          </van-cell>
          <van-cell clickable @click="payWay = 2">
            <template #title>
              <img src="@assets/images/zfb.png" alt="" />
              <span>支付宝支付</span>
            </template>
            <template #right-icon>
              <van-radio :name="2" checked-color="#07c160" />
            </template>
          </van-cell>
        </van-radio-group>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import _Ap from '@assets/js/ap';
import { Cell, Button, Radio, Dialog, RadioGroup, Field, Popup, Picker, Area, Toast } from 'vant';
import areaList from '@assets/js/city.js';
import { order_saveOrder, product_getProductDetailNew } from '@api/service';
import { pay_wxPay, pay_aliPayForWebPage } from '@api/gift';
import wx from 'weixin-js-sdk';
export default {
  components: {
    [Dialog.Component.name]: Dialog.Component,
    [Area.name]: Area,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Field.name]: Field,
    [Button.name]: Button,
    [Cell.name]: Cell
  },
  data() {
    return {
      orderId: '', //生成的订单id
      showPayDialog: false, //展示支付弹窗
      payWay: 1, // 1微信 2支付宝
      areaList: areaList,
      area: { show: false },
      note: '', //订单留言
      totalFee: this.$route.query.totalFee,
      address: '' // 详细地址
    };
  },
  methods: {
    //确认吊起支付
    handlePay(action, done) {
      const { payWay } = this;
      if (action === 'confirm') {
        done(true);
        if (payWay === 1) {
          this.$loading.show();
          this.payWx();
        } else {
          this.payZfb();
        }
      } else {
        done(true);
      }
    },
    //支付宝支付
    payZfb() {
      pay_aliPayForWebPage({ orderId: this.orderId, totalFee: this.totalFee, productName: '企业服务礼包', returnUrl: location.origin + process.env.BASE_URL + 'zfbSuccess' }).then(res => {
        const div = document.createElement('div');
        div.innerHTML = res;
        div.id = 'alipay';
        document.body.append(div);
        // document.forms[0].acceptCharset = 'utf-8';
        // document.forms[0].submit();
        var queryParam = '';
        Array.prototype.slice.call(document.querySelectorAll('input[type=hidden]')).forEach(function(ele) {
          queryParam += '&' + ele.name + '=' + encodeURIComponent(ele.value);
        });
        var gotoUrl = document.querySelector('#alipay form').action + '&' + queryParam;
        _AP.pay(gotoUrl, this.orderId);
      });
    },
    //微信支付
    payWx() {
      const that = this;
      pay_wxPay({ orderId: this.orderId, totalFee: this.totalFee, productName: '企业服务礼包' }).then(res => {
        if (res.code === 200) {
          let { appId, timestamp, nonceStr, sign } = res.data;
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId, // 必填，公众号的唯一标识
            timestamp, // 必填，生成签名的时间戳
            nonceStr, // 必填，生成签名的随机串
            signature: sign, // 必填，签名
            jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
          });
          wx.ready(function() {
            wx.chooseWXPay({
              timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr, // 支付签名随机串，不长于 32 位
              package: res.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: sign, // 支付签名
              success: function() {
                that.$loading.hide();
                Toast('订单发货中');
                setTimeout(() => {
                  that.$router.openPage('/mine');
                }, 1000);
                // 支付成功后的回调函数
              },
              cancel: function() {
                that.$loading.hide();
              },
              error: function(res) {
                that.$loading.hide();
                Toast(res);
                // 支付失败的回调函数
              }
            });
          });
        } else {
          Toast(res.msg);
        }
      });
    },
    // 确认选择地址
    confirmArea(val) {
      this.area = { show: false, province: val[0].name, city: val[1].name, area: val[2].name };
    },
    async applyOrder() {
      const { phone, company, nickname } = this.userInfo;
      const { area, note, address } = this;
      if (!area.province) {
        return Toast('请选择收货地址');
      } else if (!address) {
        return Toast('请填写详细地址');
      }
      let res = await order_saveOrder({
        json: 1,
        productId: 23,
        phone,
        company,
        nickname,
        status: 1,
        detailList: [
          { itemKey: 'address', itemValue: area.province + area.city + area.area + address, itemName: '收货地址' },
          { itemKey: 'note', itemValue: note, itemName: '订单留言' }
        ]
      });
      if (res.code === 200) {
        this.orderId = res.data;
        this.showPayDialog = true;
      } else {
        Toast(res.msg);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.apply-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  font-size: 30px;
  font-weight: bold;
}
.address {
  margin-bottom: 20px;
  background: #fff;
  .van-cell:nth-child(2):after {
    border-bottom: none;
  }
}
.line {
  height: 6px;
  width: 100%;
}
.order-detail {
  background: #fff;
  padding: 20px 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 26px;
  color: #a4abb4;
  .left {
    display: flex;
    align-items: center;
    height: 163px;
  }
  .order-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .order-content p:first-child {
    color: #000000;
    font-size: 28px;
    margin-bottom: 32px;
  }
  img {
    width: 163px;
    height: 163px;
    margin-right: 50px;
  }
}
.dialog-container {
  margin: 30px 0;
  .van-cell__title {
    display: flex;
    align-items: center;
  }
  img {
    width: 72px;
    height: 72px;
    margin-right: 20px;
  }
  .van-cell {
    padding: 32px;
  }
}
</style>
